import os
import json
import shutil

def split_mobvoi():
# 定义文件路径
    dataset_dir = "mobvoi_hotword_dataset"  # 音频文件所在的文件夹
    json_files = {
        "n_dev": "n_dev.json",
        "n_test": "n_test.json",
        "n_train": "n_train.json",
        "p_dev": "p_dev.json",
        "p_test": "p_test.json",
        "p_train": "p_train.json"
    }

    # 定义 keyword_id 到文件夹名称的映射
    keyword_to_dir = {
        -1: "_unknown_",
        0: "hixiaowen",
        1: "nihaowenwen"
    }

    # 定义输出文件夹结构
    output_dirs = {
        "n_dev": "dev",
        "n_test": "test",
        "n_train": "train",
        "p_dev": "dev",
        "p_test": "test",
        "p_train": "train"
    }

    # 创建目标文件夹
    for output_dir in set(output_dirs.values()):
        for keyword_dir in keyword_to_dir.values():
            os.makedirs(os.path.join(output_dir, keyword_dir), exist_ok=True)

    # 处理每个 JSON 文件
    for prefix, json_file in json_files.items():
        with open(os.path.join("mobvoi_hotword_dataset_resources",json_file), "r", encoding="utf-8") as f:
            data = json.load(f)

        for item in data:
            utt_id = item["utt_id"]
            keyword_id = item["keyword_id"]

            # 源文件路径
            src_file = os.path.join(dataset_dir, f"{utt_id}.wav")  # 假设音频文件是 .wav 格式
            if not os.path.exists(src_file):
                print(f"警告：文件 {src_file} 不存在，跳过")
                continue

            # 目标文件夹路径
            target_dir = os.path.join(output_dirs[prefix], keyword_to_dir[keyword_id])
            target_file = os.path.join(target_dir, f"{utt_id}.wav")

            # 复制文件
            shutil.copy(src_file, target_file)
            print(f"已复制：{src_file} -> {target_file}")
    print("处理完成！")

def filter_short(directory):
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.lower().endswith('.wav') and os.path.getsize(os.path.join(root,file))>93*1024 :
                os.makedirs(os.path.join("long",root),exist_ok=True)
                shutil.move(os.path.join(root,file),os.path.join("long",root,file))
filter_short("train")
filter_short("dev")
filter_short("test")

